package org.mikrosopht.client;

import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.RadioButton;
import com.google.gwt.user.client.ui.Widget;

public class MovieListSorter extends Composite implements ClickListener {
  private HorizontalPanel panel = new HorizontalPanel();
  private MovieListSorterEventReceiver receiver;

  private RadioButton tallySort = new RadioButton("sorting", "Sort by tally (descending) and name (ascending)");
  private RadioButton newestSort = new RadioButton("sorting", "Sort by newest movies");
  private RadioButton reviewSort = new RadioButton("sorting", "Sort by review score");

  public enum Button { TALLY, NEWEST, REVIEW };

  public MovieListSorter(MovieListSorterEventReceiver receiver) {
    this.receiver = receiver;
    panel.add(tallySort);
    panel.add(newestSort);
    panel.add(reviewSort);
    tallySort.setChecked(true);
    
    tallySort.addClickListener(this);   
    newestSort.addClickListener(this);   
    reviewSort.addClickListener(this);   
    initWidget(panel);
  }

  public void onClick(Widget sender) {
    Button clicked = null;
    if (sender == tallySort) {
      clicked = Button.TALLY;
    } else if (sender == newestSort) {
      clicked = Button.NEWEST;
    } else if (sender == reviewSort) {
      clicked = Button.NEWEST;
    }
    if (clicked != null) {
      receiver.onClick(clicked);
    }
  }

  public void setChecked(Button button) {
    switch (button) {
      case TALLY:
        tallySort.setChecked(true);
        break;
      case NEWEST:
        newestSort.setChecked(true);
        break;
      case REVIEW:
        reviewSort.setChecked(true);
        break;
    }
  }

  public Button getChecked() {
    if (tallySort.isChecked()) {
      return Button.TALLY;
    } else if (newestSort.isChecked()) {
      return Button.NEWEST;
    } else if (reviewSort.isChecked()) {
      return Button.REVIEW;
    }
    return null;
  }
}
